package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.vo.LoginVO;
import com.heima.user.mapper.UserMapper;
import com.heima.user.service.UserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-09-12 11:13
 */
@Service
@Slf4j //日志注解
public class UserServiceImpl extends ServiceImpl<UserMapper, ApUser> implements UserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public LoginVO login(LoginDto loginDto) {

        LoginVO loginVO = new LoginVO();

        String password = loginDto.getPassword();
        String phone = loginDto.getPhone();
        //0.判断是游客登录还是用户登陆
        if(StringUtils.isNotBlank(phone) && StringUtils.isNotBlank(password)){
            //用户登陆

            //1.根据手机号查询数据库
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
            //2.校验数据是否存在，不存在手机号错误
            if(apUser == null){
                throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //3.将前端明文密码 + 后端salt盐值，用md5加密，生成前端加密后的密码
            String frontPassword = DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes(StandardCharsets.UTF_8));
            //4比对前端和后端密码，如果不一致，返回错误
            if(!frontPassword.equals(apUser.getPassword())){
                throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //5.返回数据给前端 token（详细看接口文档）

            //给数据脱敏
            apUser.setSalt("");
            apUser.setPassword("");
            loginVO.setUser(apUser);
            loginVO.setToken(AppJwtUtil.getToken(Long.valueOf(apUser.getId())));

        }else{
            //游客登录
            loginVO.setToken(AppJwtUtil.getToken(0L));
        }

        return loginVO;
    }

    @Override
    public void follow(UserRelationDto dto) {
        //1.校验用户登陆状态
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null || user.getId() == null){
            //未登录
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.存储点赞数据 set
        String userId = user.getId().toString();
        String authorId = dto.getAuthorId().toString();

        BoundSetOperations<String, String> setFollow = stringRedisTemplate.
                boundSetOps(BehaviorConstants.APUSER_FOLLOW_RELATION + userId);

        BoundSetOperations<String, String> setFans = stringRedisTemplate.
                boundSetOps(BehaviorConstants.APUSER_FANS_RELATION + authorId);

        if(dto.getOperation() == 0){
            //写入关注数据
            setFollow.add(authorId);
            setFans.add(userId);
        }else if(dto.getOperation() == 1){
            //删除数据
            setFollow.remove(authorId);
            setFans.remove(userId);
        }
    }

    public static void main(String[] args) {
        System.out.println(AppJwtUtil.getToken(0L));
    }
}
